package com.ficv.tucanalmovil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.provider.Settings.Secure;
import android.util.Log;

public class MiService  extends Service {
		   
		  private static final String MiService = MiService.class.getSimpleName();
		   
		  private Timer timer;
		  
		  private String msg="";
		   
		  private TimerTask updateTask = new TimerTask() {
		    @Override
		    public void run() {
		      Log.i(MiService, "Timer task doing work");
		      synchronized (serviceLock) {
				    
		    	    //getOtherMsg();
		    	  getNewAvisos();
		    	}
		    		
		    }

			
		  };
		   
		  private void getOtherMsg() {
				String newmsg=getMsg();
				
				//Log.i(MiService, newmsg + "/" + msg);
				
				if(newmsg!=null &&  !newmsg.equalsIgnoreCase("") && !newmsg.equalsIgnoreCase(msg)) {
					
					if(!msg.equalsIgnoreCase("")) {
						msg=newmsg; Log.i(MiService, "so, notify");
						notifica();	   
					}
					else msg=newmsg;

				}
			}

		  
		  private void getNewAvisos() {
				String newmsg=getMsg();
				
				//Log.i(MiService, newmsg + "/" + msg);
				
				if(newmsg!=null &&  !newmsg.equalsIgnoreCase("") && !newmsg.equalsIgnoreCase(msg)) {
					
					if(!msg.equalsIgnoreCase("")) {
						msg=newmsg; Log.i(MiService, "so, notify");
						notifica();	   
					}
					else msg=newmsg;

				}
			}

		  
private final Object serviceLock = new Object();


	  
		  @Override
		  public IBinder onBind(Intent intent) {
		    // TODO Auto-generated method stub
		    return null;
		  }
		 
		  public void notifica() {
			  String ns = Context.NOTIFICATION_SERVICE;
	    		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
	    		
	    		int icon = R.drawable.ic_launcher;
	    		CharSequence tickerText = "Nuevo aviso de tucanalmovil";
	    		long when = System.currentTimeMillis();

	    		Notification notification = new Notification(icon, tickerText, when);
	    		
	    		Context context = getApplicationContext();
	    		CharSequence contentTitle = "Avisos de tu canal móvil";
	    		CharSequence contentText=msg;
	    		Intent notificationIntent = new Intent(this, AvisoActivity.class);
	    		notificationIntent.putExtra("NotificationMessage", msg);
	    		notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    		notification.flags |= Notification.FLAG_AUTO_CANCEL;

	    		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


	    		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
	    			    		

	    		mNotificationManager.notify(101, notification);

		}

		@Override
		  public void onCreate() {
		    super.onCreate();
		    Log.i(MiService, "Service creating");
		     
		    timer = new Timer("avisosTimer");
		    timer.schedule(updateTask, 1000L, 30 * 1000L);
		  }
		 
		  @Override
		  public void onDestroy() {
		    super.onDestroy();
		    Log.i(MiService, "Service destroying");
		     
		    timer.cancel();
		    timer = null;
		  }

		   protected String getMsg() 
			{
			   	String result="";
				try 
				{
					String androidId=Secure.getString(getContentResolver(), Secure.ANDROID_ID);				
					String url = Utils.getUrlContent(MainActivity.URL_BASE);
					result= Utils.getUrlContent(url + "msg?androidId=" + androidId);
					
				} 
				catch(Exception e) 
				{
					Log.e("MiService", e.getMessage(), e);
				} 
				
				return result.toString();	
			}


		   protected AvisosList getAvisos(String code) 
			{
				try 
				{
					// The URL for making the GET request
					//final String url = "http://192.168.2.102/" + code + ".xml";
					
					String androidId=Secure.getString(getContentResolver(), Secure.ANDROID_ID);	
					String url = Utils.getUrlContent(MainActivity.URL_BASE) + "allmsg?androidId=" + androidId + "&last=0";

					
					// Set the Accept header for "application/xml"
					HttpHeaders requestHeaders = new HttpHeaders();
					List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
					acceptableMediaTypes.add(MediaType.APPLICATION_XML);
					requestHeaders.setAccept(acceptableMediaTypes);
					
					// Populate the headers in an HttpEntity object to use for the request
					HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
					
					// Create a new RestTemplate instance
					RestTemplate restTemplate = new RestTemplate();
					
					// Perform the HTTP GET request
					ResponseEntity<AvisosList> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, AvisosList.class);
					
					// Return the list of states
					AvisosList avs = responseEntity.getBody();

					return avs;
				} 
				catch(Exception e) 
				{
					Log.e("TAG", e.getMessage(), e);
				} 
				
				return null;
			}		   
		   
		   

}


